/*
 * @Author: wgl
 * @Date: 2025-03-08 22:55:51
 * @Description: 
 * 
 */
/*
 * @Author: AI Assistant
 * @Description: 全局时间格式化拦截器
 */
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import dayjs from 'dayjs';

@Injectable()
export class DateFormatInterceptor implements NestInterceptor {
    private readonly dateFormat = 'YYYY-MM-DD HH:mm:ss';

    private formatDate(data: any): any {
        if (data === null || data === undefined) {
            return data;
        }

        if (data instanceof Date) {
            return dayjs(data).format(this.dateFormat);
        }

        if (Array.isArray(data)) {
            return data.map(item => this.formatDate(item));
        }

        if (typeof data === 'object') {
            const formatted = {};
            for (const key in data) {
                if (Object.prototype.hasOwnProperty.call(data, key)) {
                    formatted[key] = this.formatDate(data[key]);
                }
            }
            return formatted;
        }

        return data;
    }

    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        return next.handle().pipe(
            map(data => this.formatDate(data))
        );
    }
}